/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.chl.da.filters;

import edu.chl.da.controllerBeans.LoginBean;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Filter stopping users to access non authorized pages or information
 * @author Kristofer
 */

@WebFilter("*.jsf")
public class LoginAuthentication implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession httpSession = httpRequest.getSession();
        String servletPath = httpRequest.getServletPath();

        LoginBean bean = (LoginBean) httpSession.getAttribute("LoginBean");

        if(bean == null){
             chain.doFilter(request, response);
             return;
        }
        else if (servletPath.contains("/admin/") && !bean.isLoggedIn()){
            httpResponse.sendRedirect("/AirlineBooking-web/views/home.jsf");
        }
        else if(servletPath.contains("/admin/")  && !bean.getAuthenticationLevel().equals("agent")){
            httpResponse.sendRedirect("/AirlineBooking-web/views/home.jsf");
        }
        else if(servletPath.contains("/myReservations.jsf")  && !bean.isLoggedIn()){
            httpResponse.sendRedirect("/AirlineBooking-web/views/home.jsf");
        }
        else if(servletPath.contains("/myReservations.jsf")  && !bean.getAuthenticationLevel().equals("customer")){
            httpResponse.sendRedirect("/AirlineBooking-web/views/home.jsf");
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
